package de.eventdroid;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.NameValuePair;

import de.eventdroid.helper_classes.GeoDataHandler;
import de.eventdroid.helper_classes.JSONHandler;
import de.eventdroid.helper_classes.RESTHandler;
import de.eventdroid.helper_classes.TextHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class LocationResultScreen extends Activity {
	
	/**
	 * Declaration of needed variables
	 */
	private String resultString = null;
	private ArrayList<String> aktFoundObjectsForListViewArray = new ArrayList<String>();
	private ArrayList<String> aktFoundObjectIDs = new ArrayList<String>();
	private ListAdapter listenAdapter = null;
	private ArrayAdapter<String> locationArrayAdapter = null;
	private ListView aktListView;
	private Intent showSpecLocationData;
	private String searchParameter;
	private String searchMode;
	private Point act_location_gps_position;
	private double act_location_latitude;
	private double act_location_longitude;
	private static final double ROUNDING_FACTOR = 1e6;
	public LocationResultScreen local_activity;
	
	/* Loading dialog */
	ProgressDialog dialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.eventdroid_location_result_screen);
        
        /* local activity */
        local_activity = this;
        
        this.fetchLocationResultsForListView();
        
        aktListView = (ListView)findViewById(R.id.listview_location_result_list_view);
    	showSpecLocationData = new Intent(this, LocationSpecialResultScreen.class);
		
    	aktListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View aktView, int clickedPosition,
					long arg3) {
				
				/* show loading dialog */
				dialog = ProgressDialog.show(local_activity, "", "Bitte warten, Detaildaten werden geladen....", true);
				
				aktListView.getItemAtPosition(clickedPosition);						
				showSpecLocationData.putExtra("location_data", aktFoundObjectIDs.get(clickedPosition));
				dialog.cancel();
				startActivity(showSpecLocationData);
				
			}
		});
        
    }
    
    /**
     * Worker Class for fetching the Location Results for ListView 
     */
	private void fetchLocationResultsForListView() {
	    	
		/* Fetch assigned data of the special Location */
        searchMode = getIntent().getExtras().getString("search_mode");
        
		/* check which search mode was selected */
		if(searchMode.equals("gps")) { 
			
			/* Get the ambit of the search */
			searchParameter = getIntent().getExtras().getString("gps_ambit");
			
			/* Get GPS data from GeoDataHandler */
			act_location_gps_position = GeoDataHandler.getActualGPSPosition(this);
			
			/* Get latitude and longitude from geopoint */
			act_location_latitude = (act_location_gps_position.x)/ROUNDING_FACTOR;
			act_location_longitude = (act_location_gps_position.y)/ROUNDING_FACTOR; 

			/* Fetch ressources data from Server */
	    	resultString = RESTHandler.getData("locationHandler/radius/"+searchParameter+"/"+act_location_latitude+"/"+act_location_longitude);
	    	
		} else {
			
			String loc_zipCode = "";
	    	String loc_category = "";
	    	String loc_town = "";
	    	String loc_name = "";
			
			/* Fetch ressources data from Server */
			/* TODO different between ZIP / CAT / NAME / TOWN */
	    	loc_zipCode = searchParameter = getIntent().getExtras().getString("loc_zipCode");
	    	loc_name = searchParameter = getIntent().getExtras().getString("loc_name");
	    	loc_town = searchParameter = getIntent().getExtras().getString("loc_town");
	    	loc_category = searchParameter = getIntent().getExtras().getString("loc_category");
			
	    	/* clearing empty parameters for recognition by the web service */
	    	if (loc_zipCode.equals("")) { loc_zipCode = "0"; }
	    	if (loc_name.equals("")) { loc_name = "0"; }
	    	if (loc_town.equals("")) { loc_town = "0"; }
	    	if (loc_category.equals("")) { loc_category = "0"; }
	    	
	    	/* request the data */
	    	resultString = RESTHandler.getData("locationHandler/individual/"+loc_zipCode+"/"+loc_town+"/"+loc_name+"/"+loc_category);
		}
    	
    	/* Parse the JSON String into  */
    	aktFoundObjectsForListViewArray = JSONHandler.parseJSONDataForListView(resultString, "location", true);
    	
    	/* Extract Location IDs from content */
    	aktFoundObjectIDs = TextHandler.extractIDFromResultArray(aktFoundObjectsForListViewArray);
    	
    	/* Cleanup List Location from IDs */
    	aktFoundObjectsForListViewArray = TextHandler.cleanUpArrayFromIds(aktFoundObjectsForListViewArray);
    	
	    /* Allocate ListAdapter for filling the ListView */
	    aktListView = (ListView) findViewById(R.id.listview_location_result_list_view);
	    locationArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, aktFoundObjectsForListViewArray);
	    locationArrayAdapter.notifyDataSetChanged();
	    listenAdapter = locationArrayAdapter;
	    aktListView.setAdapter(listenAdapter);
	    
	    /* Number of found Locations in Toast */
	    Toast.makeText(getBaseContext(), "Es wurden "+aktFoundObjectsForListViewArray.size()+" Locations gefunden." ,Toast.LENGTH_LONG).show();
		
    }
	
	/**
	 * Creation Class for the menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
			case R.id.menu_startscreen:     
				startActivity(new Intent(this, StartScreen.class));           	
				break;
		}
		return true;
	}
}